package com.gitee.feizns.web.ex.impl;

import com.gitee.feizns.web.domain.result.Err;
import com.gitee.feizns.web.domain.result.Ret;
import com.gitee.feizns.web.ex.CustomizeExceptionHandler;
import com.gitee.feizns.web.ex.GlobalRestfulExceptionAdvice;
import com.gitee.feizns.web.ex.HttpException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;

/**
 * @author feizns
 * @since 2019/7/7
 */
public class HttpExceptionHandler implements CustomizeExceptionHandler<HttpException, Object> {

    @Override
    public ResponseEntity<Ret<Object>> handle(HttpException e) {
        HttpStatus status = e.getStatus();

        ResponseEntity ret = GlobalRestfulExceptionAdvice.errorMappingHandle(e, err -> ResponseEntity.status(status).body(Ret.err(err)));
        if ( ret != null )
            return ret;

        Err err = e.getErr();
        if ( err != null )
            return ResponseEntity.status(status).body(Ret.err(e.getErr()));

        String message = e.getMessage();
        if ( message == null )
            message = CustomizeExceptionHandler.defaultMsg(e);

        return ResponseEntity.status(e.getStatus()).body(Ret.err(status.value(), message));
    }

}
